﻿//Copyright md bravo - feel free to modify this code in any way - just leave this notice ;)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ShareCDN.Engine.Web
{
	public class UploadManager
	{
		const string SessionKey = "currentUploadManager__";
		public static UploadManager Current
		{
			get
			{
				var session = System.Web.HttpContext.Current.Session;
				var mngr = session[SessionKey] as UploadManager;
				if (mngr == null)
				{
					mngr = new UploadManager();
					session[SessionKey] = mngr;
				}
				return mngr;
			}
		}


		System.Collections.Concurrent.ConcurrentDictionary<string, UploadSlot> _slots = new System.Collections.Concurrent.ConcurrentDictionary<string, UploadSlot>();

		public UploadSlot GetUploadSlotForFile(string fileName)
		{
			UploadSlot slot = null;
			if (!_slots.TryGetValue(fileName,out slot))
			{
				slot = new UploadSlot();
				_slots[fileName] = slot;
			}
			return slot;
		
		}

		public List<UploadSlot> GetAllUploadSlots()
		{
			return _slots.Select(x => x.Value).ToList();

		}

		public string GenerateUrlForUploadedFile(UploadSlot slot)
		{
			var result=slot.Result;
			var request = System.Web.HttpContext.Current.Request;
			string httProtocol = request.Url.Port == 443 ? "https://" : "http://";
			var host = request.Params["HTTP_HOST"];
			if (slot.ForceDownload)
			{
				return httProtocol + host + "/downl?" + result.SecretKey;
			}
			else
			{ 
				
				return httProtocol + host + "/d?" + result.SecretKey;
			}

		}
	}
}
